package cn.bocweb.spinning.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.GetQaCtypeBean;
import cn.bocweb.spinning.model.Bean.QaGetCatBean;
import cn.bocweb.spinning.model.Bean.QaPublishBean;
import cn.bocweb.spinning.model.Bean.QaUserScoreBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.GvImgAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ContainsEmojiEditText;
import cn.bocweb.spinning.view.dialog.SelectCommunityDialog;
import de.greenrobot.event.EventBus;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

public class WriteQuestionActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.btn_community)
    TextView btnCommunity;
    @Bind(R.id.btn_show_pic)
    ImageView btnShowPic;
    @Bind(R.id.btn_show_money)
    ImageView btnShowMoney;
    @Bind(R.id.write_quiz_pic)
    LinearLayout writeQuizPic;
    @Bind(R.id.write_quiz_money)
    LinearLayout writeQuizMoney;
    @Bind(R.id.integral_0)
    RelativeLayout integral0;
    @Bind(R.id.integral_5)
    RelativeLayout integral5;
    @Bind(R.id.integral_10)
    RelativeLayout integral10;
    @Bind(R.id.integral_20)
    RelativeLayout integral20;
    @Bind(R.id.integral_30)
    RelativeLayout integral30;
    @Bind(R.id.integral_50)
    RelativeLayout integral50;
    @Bind(R.id.integral_70)
    RelativeLayout integral70;
    @Bind(R.id.integral_100)
    RelativeLayout integral100;

    int photo_size = 3;
    String userid;
    int myScore = 0;
    GvImgAdapter gvImgAdapter;
    SelectCommunityDialog dialog;
    List<QaGetCatBean.DataBean> list;
    List<File> mFiles;
    UserPresenter mPresenter;
    String id, score = "0";
    int photoCount = 0;
    @Bind(R.id.add_image)
    RelativeLayout mAddImage;
    @Bind(R.id.gv_img)
    RecyclerView mGvImg;
    @Bind(R.id.user_score)
    TextView mUserScore;
    @Bind(R.id.img_count)
    TextView mImgCount;
    @Bind(R.id.qa_submit)
    TextView mQaSubmit;
    @Bind(R.id.ques_edit)
    ContainsEmojiEditText mQuesEdit;
    @Bind(R.id.tv_count)
    TextView mTvCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_question);
        ButterKnife.bind(this);

        list = new ArrayList<>();
        mFiles = new ArrayList<>();
        gvImgAdapter = new GvImgAdapter(mFiles);
        mPresenter = new UserPresenterImp();
        dialog = new SelectCommunityDialog(this);

        initToolbar();
        initClickBtn();
        initGvImg();

        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();

        mPresenter.qaappGetCat();
        mPresenter.qaUserScore(userid);

        initButton(integral0);

        mQuesEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvCount.setText(String.valueOf(s.toString().length()));
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(final GetQaCtypeBean bean) {
        if (bean.getReturn_code() == 0) {
            dialog.setList(bean.getData());
            dialog.setOnSelectListener(new SelectCommunityDialog.OnSelectListener() {
                @Override
                public void onClick(int position) {
                    id = bean.getData().get(position).getId();
                    btnCommunity.setText(bean.getData().get(position).getTitle());
                }
            });
        }
    }

    public void onEventMainThread(QaUserScoreBean bean) {
        if (bean.getReturn_code() == 0) {
            myScore = Integer.parseInt(bean.getScore());
            mUserScore.setText(bean.getScore());
        }
    }

    public void onEventMainThread(QaPublishBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            finish();
        }
        mQaSubmit.setClickable(true);
    }

    public void onEventMainThread(ErrorBean bean) {
        DeviceUtil.MyToast(this, bean.getErrorMsg());
        mQaSubmit.setClickable(true);
    }

    private void initGvImg() {
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        mGvImg.setAdapter(gvImgAdapter);
        mGvImg.setLayoutManager(manager);

        gvImgAdapter.setOnItemClickListener(new GvImgAdapter.OnItemClickListener() {
            @Override
            public void onClick() {
                if (Build.VERSION.SDK_INT >= 23) {
                    int camarePermission = ContextCompat.checkSelfPermission(WriteQuestionActivity.this, Manifest.permission.CAMERA);
                    int photoPermission = ContextCompat.checkSelfPermission(WriteQuestionActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (camarePermission != PackageManager.PERMISSION_GRANTED || photoPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(
                                WriteQuestionActivity.this,
                                new String[]{
                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_EXTERNAL_STORAGE}, 301);
                        return;
                    }
                }
                PhotoPickerIntent intent = new PhotoPickerIntent(WriteQuestionActivity.this);
                intent.setPhotoCount(photo_size);
                intent.setShowCamera(true);
                intent.setShowGif(false);
                startActivityForResult(intent, Constant.SELECT_PHOTO_FOR_QA);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 301: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(WriteQuestionActivity.this);
                    intent.setPhotoCount(photo_size);
                    intent.setShowCamera(true);
                    intent.setShowGif(false);
                    startActivityForResult(intent, Constant.SELECT_PHOTO_FOR_QA);
                } else {
                    DeviceUtil.MyToast(this, "未获得相应权限");
                }
                break;
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constant.SELECT_PHOTO_FOR_QA) {
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                if (photos.isEmpty()) {
                    mImgCount.setVisibility(View.GONE);
                } else {

                    mImgCount.setVisibility(View.VISIBLE);

                    mGvImg.setVisibility(View.VISIBLE);
                    mAddImage.setVisibility(View.GONE);
                    for (String filePath : photos) {
                        File file = new File(filePath);
                        mFiles.add(file);
                    }
                    photo_size = 3 - mFiles.size();
                    mImgCount.setText(String.valueOf(mFiles.size()));
                    photoCount = mFiles.size();
                    gvImgAdapter.notifyDataSetChanged();
                    gvImgAdapter.setOnImgDeleteListener(new GvImgAdapter.OnImgDeleteListener() {
                        @Override
                        public void onclick(int position) {
                            mFiles.remove(position);
                            photo_size++;
                            photoCount = mFiles.size();
                            mImgCount.setText(String.valueOf(mFiles.size()));
                            gvImgAdapter.notifyDataSetChanged();
                            if (mFiles.size() == 0) {
                                mImgCount.setVisibility(View.GONE);
                                mAddImage.setVisibility(View.GONE);
                            } else {
                                mImgCount.setVisibility(View.VISIBLE);
                                mAddImage.setVisibility(View.GONE);
                            }
                        }
                    });
                }
            }
        }
    }

    private void initClickBtn() {
        btnCommunity.setOnClickListener(this);
        btnShowPic.setOnClickListener(this);
        btnShowMoney.setOnClickListener(this);
        mQaSubmit.setOnClickListener(this);
        integral0.setOnClickListener(this);
        integral5.setOnClickListener(this);
        integral10.setOnClickListener(this);
        integral20.setOnClickListener(this);
        integral30.setOnClickListener(this);
        integral50.setOnClickListener(this);
        integral70.setOnClickListener(this);
        integral100.setOnClickListener(this);
        mAddImage.setOnClickListener(this);
    }

    private void initToolbar() {
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setTitle("描述你的问题");
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_community: {
                dialog.show();
                break;
            }
            case R.id.btn_show_pic: {
                writeQuizMoney.setVisibility(View.GONE);
                writeQuizPic.setVisibility(View.VISIBLE);

                break;
            }
            case R.id.btn_show_money: {
                writeQuizPic.setVisibility(View.GONE);
                writeQuizMoney.setVisibility(View.VISIBLE);
                break;
            }
            case R.id.integral_0: {
                initButton(integral0);
                score = "0";
                break;
            }
            case R.id.integral_5: {
                if (myScore >= 5) {
                    initButton(integral5);
                    score = "5";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.integral_10: {
                if (myScore >= 10) {
                    initButton(integral10);
                    score = "10";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.integral_20: {
                if (myScore >= 20) {
                    initButton(integral20);
                    score = "20";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.integral_30: {
                if (myScore >= 30) {
                    initButton(integral30);
                    score = "30";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.integral_50: {
                if (myScore >= 50) {
                    initButton(integral50);
                    score = "50";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.integral_70: {
                if (myScore >= 70) {
                    initButton(integral70);
                    score = "70";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.integral_100: {
                if (myScore >= 100) {
                    initButton(integral100);
                    score = "100";
                } else {
                    scoreNotEnough();
                }
                break;
            }
            case R.id.add_image: {
                PhotoPickerIntent intent = new PhotoPickerIntent(WriteQuestionActivity.this);
                intent.setPhotoCount(photo_size);
                intent.setShowCamera(true);
                intent.setShowGif(false);
                startActivityForResult(intent, Constant.SELECT_PHOTO_FOR_QA);
                break;
            }
            case R.id.qa_submit: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                if (TextUtils.isEmpty(id)) {
                    DeviceUtil.MyToast(this, "请选择社区");
                    break;
                }
                if (TextUtils.isEmpty(mQuesEdit.getText().toString())) {
                    DeviceUtil.MyToast(this, "请输入问题");
                    break;
                }
                mPresenter.qaPublish(dataEntity.getUserid(), id, score, mQuesEdit.getText().toString(), mFiles);
                mQaSubmit.setClickable(false);
                break;
            }
        }
    }

    private void initButton(RelativeLayout rl) {
        integral0.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral0.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral5.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral5.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral10.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral10.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral20.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral20.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral30.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral30.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral50.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral50.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral70.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral70.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        integral100.setBackgroundResource(R.drawable.bg_price_select_no);
        ((TextView) integral100.getChildAt(0)).setTextColor(getResources().getColor(R.color.content));

        rl.setBackgroundResource(R.drawable.bg_price_select);
        ((TextView) rl.getChildAt(0)).setTextColor(getResources().getColor(R.color.white));

    }

    private void scoreNotEnough() {
        initButton(integral0);
        DeviceUtil.MyToast(this, "积分不足");
    }
}
